// pages/user/userinfo.js
const userManager = require('../../utils/userManager');
const api = require('../../utils/api');

Page({
  data: {
    userInfo: {
      avatar: '/images/icon/user_placeholder.png',
      nickname: '微信用户',
      phone: '',
    },
    memberInfo: {
      level: '',
      points: 0,
      registerTime: ''
    },
    isLoading: true
  },

  onLoad: function (options) {
    // 页面加载时获取用户信息
    this.getUserInfo();
  },

  getUserInfo: function () {
    this.setData({ isLoading: true });
    
    // 首先从本地获取基本用户信息
    const localUserInfo = userManager.getUserInfo();
    if (localUserInfo) {
      this.setData({
        userInfo: {
          ...this.data.userInfo,
          avatar: localUserInfo.avatar || this.data.userInfo.avatar,
          nickname: localUserInfo.name || localUserInfo.nickname || this.data.userInfo.nickname,
          phone: localUserInfo.phone || this.data.userInfo.phone
        }
      });
    }
    
    // 从服务器获取完整用户信息
    Promise.all([
      api.user.getUserInfo(),
      api.user.getAccountInfo()
    ])
    .then(([userRes, accountRes]) => {
      if (userRes && userRes.success && userRes.data) {
        this.setData({
          userInfo: {
            avatar: userRes.data.avatar || this.data.userInfo.avatar,
            nickname: userRes.data.name || userRes.data.nickname || this.data.userInfo.nickname,
            phone: userRes.data.phone || this.data.userInfo.phone,
            gender: userRes.data.gender || 0
          }
        });
      }
      
      if (accountRes && accountRes.success && accountRes.data) {
        const registerTime = accountRes.data.registerTime ? 
          new Date(accountRes.data.registerTime * 1000).toLocaleDateString('zh-CN') : '';
          
        this.setData({
          memberInfo: {
            level: accountRes.data.level || '普通会员',
            points: parseInt(accountRes.data.points || 0),
            registerTime: registerTime
          }
        });
      }
    })
    .catch(err => {
      console.error('获取用户信息失败', err);
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      });
    })
    .finally(() => {
      this.setData({ isLoading: false });
    });
  },

  onTapBack: function () {
    // 返回上一页
    wx.navigateBack({
      delta: 1
    });
  },

  onTapLogout: function () {
    // 弹出确认对话框
    wx.showModal({
      title: '确认注销',
      content: '确定要注销账号吗？',
      success: (res) => {
        if (res.confirm) {
          // 用户点击确定，执行注销操作
          this.doLogout();
        }
      }
    });
  },

  doLogout: function () {
    wx.showLoading({
      title: '注销中...',
    });
    
    // 调用登出接口
    api.user.logout()
      .then(res => {
        if (res && res.success) {
          // 清除本地存储的用户信息
          userManager.clearLoginState();
          
          // 显示成功提示
          wx.showToast({
            title: '注销成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              // 跳转到登录页面
              setTimeout(() => {
                wx.reLaunch({
                  url: '/pages/user/index',
                });
              }, 2000);
            }
          });
        } else {
          wx.showToast({
            title: res.message || '注销失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('注销失败', err);
        wx.showToast({
          title: '注销失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  }
});